package com.example.securityconfig.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.example.securityconfig.entity.LoginUser;
import com.example.securityconfig.entity.User;
import com.example.securityconfig.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Objects;

@Service
public class SecurityLoginService implements UserDetailsService {
 
    @Autowired
    private UserMapper userMapper;
 
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> usersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据用户名称查询用户信息
        usersLambdaQueryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(usersLambdaQueryWrapper);
        // users==null登录失败，users！=null登陆成功
        if(Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // TODO: 2024/1/24 暂时将数据库密码进行加密,后续需要添加员工的时候加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        // 获取用户权限信息
        Integer root = user.getRoot();
        String[] roots = {"sysAdmin","manage","user"};
        ArrayList<String> strings = new ArrayList<>();
        if(root == 1){
            strings.add(roots[0]);
            strings.add(roots[1]);
            strings.add(roots[2]);
        }else if(root==2){
            strings.add(roots[1]);
            strings.add(roots[2]);
        }else if(root==3){
            strings.add(roots[2]);
        }
        return new LoginUser(user,strings);
    }
}